package com.utstarcom.util;

import com.utstarcom.hdfs.CompressFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import static com.google.common.io.Resources.getResource;

/**
 * Created by Venn on 2018/6/2.
 *
 * 获取所有配置常量
 */
public class Common {
    // 常量存放map
    private static Logger logger = LogManager.getLogger(Common.class.getName());

    private static Map<String,String> commonMap = new HashMap<String, String>();
    static Map<String,String> sysEnv = null;
    public static String proPath ="/opt/hadoop/tmp/venn/";
    public static String proPath2 ="D:\\SVN\\compresshdfsfile\\src\\main\\resources\\";

    private Common(){
    }

    static {
        logger.info("start init : " );
//        String path = Common.class.getClassLoader().getResource("").getPath();
//        System.out.println("Class Loader path : " + path);
        File file = new File(proPath);
        String currentPath;
        if(file.exists() && file.isDirectory()) {
            currentPath = proPath ;
        }else {
            currentPath = proPath2;
        }

        logger.info("properties path : " + currentPath);
//        if(currentPath.contains(":")){
//            currentPath = currentPath.substring(currentPath.indexOf(":")+1);
//        }

        init(currentPath);
        initSys(currentPath);

    }

    private static void initSys(String currentPath) {

        sysEnv = System.getenv();
        logger.info("get System enviroment : " + sysEnv.size());
//        sysEnv.put("HADOOP_HOME","/opt/hadoop/hadoop-2.7.2");
    }

    // hdfs.properties
    private static void init(String currentPath) {

        System.out.println(currentPath+"hdfs.properties");

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(currentPath+"hdfs.properties"));

            Iterator<Object> iterable = properties.keySet().iterator();

            while (iterable.hasNext()){

                String key =  iterable.next().toString();
                System.out.println(key);
                commonMap.put(key, properties.getProperty(key));
            }



        } catch (IOException e) {
            logger.error(e.getMessage());
            System.exit(-1);

        }
    }

    public static Map<String, String> getCommonMap() {
        logger.info("properties path : " + commonMap);
        return commonMap;
    }
    public static String getSysEnv(String var) {
        return sysEnv.get(var);
    }
}
